# utils/oss_utils.py
import oss2
from django.conf import settings
from datetime import datetime, timedelta

class OSSManager:
    def __init__(self):
        self.auth = oss2.Auth(
            settings.OSS_ACCESS_KEY_ID,
            settings.OSS_ACCESS_KEY_SECRET
        )
        self.bucket = oss2.Bucket(
            self.auth,
            settings.OSS_ENDPOINT,
            settings.OSS_BUCKET_NAME
        )

    def generate_presigned_url(self, object_key, expiration=None):
        """生成预签名URL"""
        if expiration is None:
            expiration = settings.OSS_URL_EXPIRATION

        # 生成预签名URL
        url = self.bucket.sign_url('GET', object_key, expiration)
        return url

    def generate_video_url(self, object_key, expiration=None):
        """生成视频URL（可扩展为HLS格式）"""
        # 如果是HLS格式，使用m3u8文件的路径
        if object_key.endswith('.mp4'):
            # 这里可以添加转码逻辑，生成HLS路径
            # 例如: object_key = object_key.replace('.mp4', '/index.m3u8')
            pass
        return self.generate_presigned_url(object_key, expiration)

    def list_objects(self, prefix=''):
        """列出存储桶中的对象"""
        objects = []
        for obj in oss2.ObjectIterator(self.bucket, prefix=prefix):
            objects.append({
                'key': obj.key,
                'size': obj.size,
                'last_modified': obj.last_modified
            })
        return objects